<template>
  <div class="user-index">
    <el-card class="page-card">
      <div class="page-header">
        <h2>用户管理</h2>
        <el-button type="success" @click="showAddDialog" icon="Plus">新增用户</el-button>
      </div>

      <!-- 查询表单 -->
      <el-form :model="user" ref="ruleFormRef" label-width="120px" label-position="right" class="search-form">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="用户名称" prop="yhm">
              <el-input v-model="user.yhm" placeholder="请输入用户名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="手机号" prop="sjh">
              <el-input v-model="user.sjh" placeholder="请输入手机号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="search-buttons">
            <el-space>
              <el-button type="primary" @click="doList" icon="Search">查询</el-button>
              <el-button type="default" @click="doFormReset" icon="Refresh">重置</el-button>
            </el-space>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" stripe hover-row border style="width: 100%" class="data-table">
        <el-table-column type="index" label="序号" width="80" align="center"/>
<!--        <el-table-column prop="id" label="ID" align="center"/>-->
        <el-table-column prop="yhm" label="用户名称" align="center"/>
        <el-table-column prop="sjh" label="手机号" align="center"/>
        <el-table-column prop="age" label="年龄" align="center"/>
        <el-table-column prop="sex" label="性别" align="center">
          <template #default="scope">
            {{ scope.row.sex === '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <el-space size="small">
              <el-button type="primary" size="small" @click="showDetailPage(scope.row)" icon="View">详情</el-button>
              <el-button type="warning" size="small" @click="showUpdateDialog(scope.row)" icon="Edit">更新</el-button>
              <el-button type="danger" size="small" @click="doDelete(scope.row.id)" icon="Delete">删除</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination">
        <el-pagination
            style="float: left;"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20, 50]"
            v-model:current-page="page.pageNum"
            v-model:page-size="page.pageSize"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增用户" width="50%" top="10vh" destroy-on-close>
      <add-page @flushPage="doFlushPage" @closeDialog="addDialogVisible = false"/>
    </el-dialog>

    <!-- 更新对话框 -->
    <el-dialog v-model="updateDialogVisible" title="更新用户" width="50%" top="10vh" destroy-on-close>
      <update-page ref="updatePageRef" @flushPage="doFlushPage" @closeDialog="updateDialogVisible = false"/>
    </el-dialog>

    <!-- 详情页面 -->
    <detail-page ref="detailPageRef"/>
  </div>
</template>

<style scoped>
.user-index {
  padding: 20px;
}

.page-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.search-form {
  padding: 0 20px 20px;
}

.search-buttons {
  display: flex;
  align-items: center;
  margin-top: -18px;
}

.data-table {
  margin: 0 20px 20px;
}

.pagination {
  margin: 20px;
  padding: 10px 0;
  background: white;
  border-top: 1px solid #ebeef5;
  position: relative;
  z-index: 1;
}
</style>

<script setup lang="ts">
import {ref, onMounted, nextTick} from 'vue'
import {ElMessage, FormInstance} from "element-plus";
import axios from 'axios'
import DetailPage from './DetailPage.vue';
import AddPage from './AddPage.vue';
import UpdatePage from './UpdatePage.vue';

// 表单对象，在 <el-form> 标签上通过 ref 绑定此对象
const ruleFormRef = ref<FormInstance>()
// 表单重置
const doFormReset = () => {
    ruleFormRef.value?.resetFields()
}

// form 查询表单绑定的数据对象
const user = ref({
    id: '',
    yhm: '',  // 改为后端实体类的属性名
    sjh: ''   // 改为后端实体类的属性名
});

// 分页相关变量
const page = ref({
    pageNum: 1,
    pageSize: 5,
    pages: 0,
    total: 0
});
// 处理分页大小变化
const handleSizeChange = (val: number) => {
    page.value.pageSize = val;
    page.value.pageNum = 1; // 重置到第一页
    doList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
    page.value.pageNum = val;
    doList();
};

// 分页重置
const doPageReset = () => {
    page.value.pageNum = 1;
    page.value.pageSize = 5;
    page.value.pages = 0;
    page.value.total = 0;
}

// table 数据表格绑定的数据对象
const tableData = ref([]);


// 查询
const loading = ref(false); // 加载状态
const doList = async () => {
    loading.value = true;
    try {
        const params = {
            ...user.value,
            pageNum: page.value.pageNum,
            pageSize: page.value.pageSize
        };

        const { data } = await axios.get('/api/users', { params });
        console.log('【前端收到响应】', data);

        if (data && data.list) {
            tableData.value = data.list;
            page.value.total = data.total || 0;
            page.value.pages = data.pages || 0;
        } else {
            tableData.value = [];
            page.value.total = 0;
            page.value.pages = 0;
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('获取数据失败');
    } finally {
        loading.value = false;
    }
};


// 刷新页面：表单重置、分页重置、重新查询
const doFlushPage = () => {
    doFormReset();
    doPageReset()
    doList();
}

// 删除
const doDelete = async (id) => {
    try {
        const { data } = await axios.delete('/api/user/' + id);

        if (data.success) {
            doFlushPage(); // 刷新页面
            ElMessage.success(data.message || '删除成功');
        } else {
            ElMessage.error(data.message || '删除失败');
        }
    } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('网络错误，请重试');
    }
}


// 初始化
onMounted(()=>{
    doList();   // 查询数据
})

//--------------------------- 新增 对话框 ---------------------------
const addDialogVisible = ref(false);
const showAddDialog = ()=>{
    addDialogVisible.value = true;
}

//--------------------------- 更新 对话框 ---------------------------
const updateDialogVisible = ref(false);
const updatePageRef = ref(); // 组件引用
const showUpdateDialog = (obj)=>{
    updateDialogVisible.value = true;
    nextTick(()=>{
        updatePageRef.value.handleUpdateData(obj);
    })
}

//--------------------------- 详显 页面---------------------------
// 详显组件引用
const detailPageRef = ref();
const showDetailPage = (obj)=>{
    detailPageRef.value.handleDetailData(obj);
}
</script>